<?php
/**
  public function create_weixin_menu(){
        $menu0 = D('weixin_menu')->where(array('parent_id'=>0))->order('sort asc')->select();
        $menu1 = D('weixin_menu')->where('parent_id<>0')->order('parent_id asc,sort asc')->select();
        $button = array();
        foreach($menu0 as $k=>$v){
            $button[] = array(
                'type'=>'click',
                'name'=>$v['name'],
                'key'=>$v['id'],
                "sub_button"=>array()
            );
        }
        foreach($menu1 as $k=>$v){
               if(isset($button[$v['parent_id']-1])){
                   $button[$v['parent_id']-1]['sub_button'][] = array(
                       'type'=>'click',
                       'name'=>$v['name'],
                       'key'=>$v['parent_id'].'_'.$v['id']
                   );
               }
        }
        $data = json_encode(['button'=>$button],JSON_UNESCAPED_UNICODE);

       $res = service('Weixin')->create_menu($data);

       if(isset($res['errcode']) && $res['errcode']==0){
           $response = array(
               'status'=>0,
               'msg'=>'更新成功',
           );
       }else{
           $response = array(
               'status'=>-1,
               'msg'=>'更新失败',
           );
       }
       $this->ajaxReturn($response);
    }
 */

/***
 * 微信公众号自定义菜单
 * Class WeixinService
 */
class WeixinService {
    //wx5719f3811146212b  f4c6f6ddfb5b962c29a6e1f2c8f3377a

    // public  $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4062d070d9c6d5c2&secret=2659a37c26ed48d1e1ec4c2d9612a4b8";//测试
   public  $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5719f3811146212b&secret=f4c6f6ddfb5b962c29a6e1f2c8f3377a";//正式
    public  $access_token = "";

    public function get_access_token(){
        $redis = new CacheRedis();
        $access_token = $redis->get("weixin_accees_token");
        if($access_token){
            return $access_token;
        }else{
            $access_token = $this->get($this->access_token_url);
            $access_token = json_decode($access_token,true);
            if($access_token){
                $redis->set("weixin_accees_token",$access_token['access_token'],$access_token['expires_in']);
            }
        }
        return $access_token['access_token'];
    }

    public function create_menu($data){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->get_access_token();
        $res = $this->post($url,$data);
        return $res;
    }




    /**
     * post 请求
     * @param $url 请求url
     * @param array $param  post参数
     * @param array $header 头部信息
     * @param bool $login   是否登陆
     * @param int $ssl      启用ssl
     * @param int $log      是否记录日志
     * @param string $format返回数据格式
     * @return mixed
     */
    function get($url,array $header_options = array(), $cookie = false)
    {
        $ch = curl_init();
        $curl_options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1, //返回原生的（Raw）输出
//            CURLOPT_HEADER => 0,
//            CURLOPT_TIMEOUT => 120, //超时时间
            CURLOPT_FOLLOWLOCATION => 1, //是否允许被抓取的链接跳转
//            CURLOPT_ENCODING=>'gzip,deflate',
//            CURLOPT_HTTPHEADER => $header_options,
        );
        if ($cookie) {
            $curl_options[CURLOPT_COOKIE] = $cookie;
        }
        if (strpos($url,"https")!==false) {
            $curl_options[CURLOPT_SSL_VERIFYPEER] = false; // 对认证证书来源的检查
        }
        curl_setopt_array($ch, $curl_options);
        $data = curl_exec($ch);
//        print_r(curl_getinfo($ch));
        curl_close($ch);
        return $data;
    }

    /**
     * post 请求
     * @param $url 请求url
     * @param array $param  post参数
     * @param array $header 头部信息
     * @param bool $login   是否登陆
     * @param int $ssl      启用ssl
     * @param int $log      是否记录日志
     * @param string $format返回数据格式
     * @return mixed
     */
    function post($url, array $param = array(), array $header = array())
    {
        $ch = curl_init();
        $post_param = array();
        if (is_array($param)) {
            $post_param = http_build_query($param);
        } else if (is_string($param)) { //json字符串
            $post_param = $param;
        }
        $header_options =  $header;
        $curl_options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1, //返回原生的（Raw）输出
            CURLOPT_HEADER => 0,
            CURLOPT_TIMEOUT => 120, //超时时间
            CURLOPT_FOLLOWLOCATION => 1, //是否允许被抓取的链接跳转
            CURLOPT_HTTPHEADER => $header_options,
            CURLOPT_POST => 1, //POST
            CURLOPT_POSTFIELDS => $post_param, //post数据
            CURLOPT_ENCODING=>'gzip,deflate'
        );

        //debug 1
//        curl_setopt($ch,CURLINFO_HEADER_OUT,1);
//        curl_setopt($ch,CURLOPT_HEADER,1);
        //debug 2 详细的请求过程
//        curl_setopt($ch,CURLOPT_VERBOSE,true);
//        curl_setopt($ch,CURLINFO_HEADER_OUT,0);
//        curl_setopt($ch,CURLOPT_HEADER,0);
//        curl_setopt($ch,CURLOPT_VERBOSE,true);
//        $fp = fopen('php://temp', 'rw+');
//        curl_setopt($ch,CURLOPT_STDERR,$fp);

        if (strpos($url,"https")!==false) {
            $curl_options[CURLOPT_SSL_VERIFYPEER] = false; // 对认证证书来源的检查
        }
        curl_setopt_array($ch, $curl_options);
        $data = curl_exec($ch);

        // $debug_info = rewind($fp) ? stream_get_contents($fp):"";
        //$debug_info = curl_getinfo($ch);
        //  print_r($debug_info);
        $data = json_decode($data, true);
        curl_close($ch);
        return $data;
    }
}